package com.tuanzi.loan.business.service.collaborate.impl;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.CurrentUser;
import com.tuanzi.loan.business.entity.LoginUser;
import com.tuanzi.loan.business.entity.collaborate.NewCollaborateChannelRatio;
import com.tuanzi.loan.business.entity.collaborate.NewCollaborateChannelUser;
import com.tuanzi.loan.business.entity.collaborate.StatCollaborateMarketLogin;
import com.tuanzi.loan.business.repository.collaborate.CollaborateChannelRatioRepository;
import com.tuanzi.loan.business.repository.collaborate.CollaborateChannelUserRepository;
import com.tuanzi.loan.business.repository.collaborate.StatCollaborateMarketLoginRepository;
import com.tuanzi.loan.business.service.collaborate.StatCollaborateMarketLoginService;
import com.tuanzi.loan.business.service.statistics.StatMarketLoginService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.service.CommonServiceImpl;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.statistics.login.StatMarketLoginRequest;
import com.tuanzi.loan.vo.response.collaborate.StatCollaborateMarketLoginResponse;
import com.tuanzi.server.loan_base.util.DateUtils;
import org.apache.commons.beanutils.BeanUtilsBean2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * User: liangZongXi
 * Create time: 11:07 2019/5/9
 * Description:
 */
@Debug
@Service
@Transactional
@Retryable(value = { RetryException.class })
public class StatCollaborateMarketLoginServiceImpl extends CommonServiceImpl<StatCollaborateMarketLogin, Long> implements StatCollaborateMarketLoginService {

    private final StatCollaborateMarketLoginRepository statCollaborateMarketLoginRepository;
    private final CollaborateChannelUserRepository collaborateChannelUserRepository;
    private final CollaborateChannelRatioRepository collaborateChannelRatioRepository;
    private final StatMarketLoginService statMarketLoginService;


    @Autowired
    public StatCollaborateMarketLoginServiceImpl(StatCollaborateMarketLoginRepository statCollaborateMarketLoginRepository,
                                                 CollaborateChannelUserRepository collaborateChannelUserRepository,
                                                 CollaborateChannelRatioRepository collaborateChannelRatioRepository, StatMarketLoginService statMarketLoginService) {
        this.statCollaborateMarketLoginRepository = statCollaborateMarketLoginRepository;
        this.collaborateChannelUserRepository = collaborateChannelUserRepository;
        this.collaborateChannelRatioRepository = collaborateChannelRatioRepository;
        this.statMarketLoginService = statMarketLoginService;
    }

    @Override
    public void statKlMarketLoginInfo(List<NewCollaborateChannelRatio> allChannelRatio, Date date) {
        if(null == allChannelRatio || allChannelRatio.size() == 0 || null == date){
            return;
        }

        List<Integer> channelList = allChannelRatio.parallelStream().map(NewCollaborateChannelRatio::getChannelId).collect(Collectors.toList());
        //查询全局渠道表-设备渠道表
        List<StatCollaborateMarketLogin> allMarketLogin = statMarketLoginService.findAllByCreateDateAndChannelIn(channelList, date);

        for (NewCollaborateChannelRatio ratioInfo : allChannelRatio) {
            Integer ratio = ratioInfo.getRatio();
            for (StatCollaborateMarketLogin marketLogin : allMarketLogin) {
                if(ratioInfo.getChannelId().toString().equals(marketLogin.getChannelCode())){
                    marketLogin.setId(null);
                    //klOperation(marketLogin, ratioInfo.getRatio());
                    marketLogin.setLoginCountA(getKlData(marketLogin.getLoginCountA(), ratio));
                    marketLogin.setLoginCountB(getKlData(marketLogin.getLoginCountB(), ratio));
                    marketLogin.setRegisterCountA(getKlData(marketLogin.getRegisterCountA(), ratio));
                    marketLogin.setRegisterCountB(getKlData(marketLogin.getRegisterCountB(), ratio));
                    marketLogin.setRegisterCountC(getKlData(marketLogin.getRegisterCountC(), ratio));
                    marketLogin.setRegisterCountD(getKlData(marketLogin.getRegisterCountD(), ratio));
                    marketLogin.setBpUvTotal(getKlData(marketLogin.getBpUvTotal(), ratio));
                    marketLogin.setBpUvApi(getKlData(marketLogin.getBpUvApi(), ratio));
                    marketLogin.setBpApiApplyCount(getKlData(marketLogin.getBpApiApplyCount(), ratio));
                    marketLogin.setBpApiLendCount(getKlData(marketLogin.getBpApiLendCount(), ratio));
                    marketLogin.setBpApiLendAmount(getKlData(marketLogin.getBpApiLendAmount(), ratio));
                }
            }
        }

        statCollaborateMarketLoginRepository.save(allMarketLogin);
    }

    @Override
    public Page<StatCollaborateMarketLoginResponse> list(PageSearcher<StatMarketLoginRequest> pageSearcher) {
        LoginUser loginUser = CurrentUser.get();
        if(null == loginUser){
            return new PageImpl<>(Lists.newArrayList());
        }

        String account = loginUser.getAccount();
        if(StringUtils.isBlank(account)){
            return new PageImpl<>(Lists.newArrayList());
        }
        //查询用户关联哪个渠道
        List<NewCollaborateChannelUser> channelUsers = collaborateChannelUserRepository.findByUserName(account);
        if(Objects.isNull(channelUsers) || channelUsers.size() <= 0){
            return new PageImpl<>(Lists.newArrayList());
        }

        List<Integer> channelList = channelUsers.stream().map(NewCollaborateChannelUser::getChannelId).collect(Collectors.toList());
        Page<StatCollaborateMarketLoginResponse> list = statCollaborateMarketLoginRepository.list(pageSearcher.getSearchCondition(),
                pageSearcher.getPageable(), channelList);

        List<NewCollaborateChannelRatio> channelRatios = collaborateChannelRatioRepository.findByChannelIdIn(channelList);

        setKlDataAndNotShowCol(list, channelRatios);

        return list;
    }

    private void setKlDataAndNotShowCol(Page<StatCollaborateMarketLoginResponse> list,  List<NewCollaborateChannelRatio> channelRatios){
        long todayTimestamp = Timestamp.valueOf(DateUtils.getCurrentDate() +" 00:00:00").getTime();
        for (NewCollaborateChannelRatio channelRatio : channelRatios) {
            Integer ratio = channelRatio.getRatio();
            String marketShow = channelRatio.getMarketShow();
            Integer channelId = channelRatio.getChannelId();
            for (StatCollaborateMarketLoginResponse response : list ) {
                if(response.getChannelCode().equals(channelId.toString())){
                    //当天的，进行扣量
                    if(response.getCreateDate().getTime() == todayTimestamp){
                        klOperation(response, ratio);
                    }

                    //置空非展示字段
                    setNullByChannelAndShowType(response, StringUtils.isBlank(marketShow) ? null : marketShow.split(","));
                }
            }
        }
    }

    private void klOperation(StatCollaborateMarketLoginResponse response, Integer ratio) {
        response.setLoginCountA(getKlData(response.getLoginCountA(), ratio));
        response.setLoginCountB(getKlData(response.getLoginCountB(), ratio));
        response.setRegisterCountA(getKlData(response.getRegisterCountA(), ratio));
        response.setRegisterCountB(getKlData(response.getRegisterCountB(), ratio));
        response.setRegisterCountC(getKlData(response.getRegisterCountC(), ratio));
        response.setRegisterCountD(getKlData(response.getRegisterCountD(), ratio));
        response.setBpUvTotal(getKlData(response.getBpUvTotal(), ratio));
        response.setBpUvApi(getKlData(response.getBpUvApi(), ratio));
        response.setBpApiApplyCount(getKlData(response.getBpApiApplyCount(), ratio));
        response.setBpApiLendCount(getKlData(response.getBpApiLendCount(), ratio));
        response.setBpApiLendAmount(getKlData(response.getBpApiLendAmount(), ratio));

    }

    private Integer getKlData(Integer source, Integer ratio){
        if(null != source && null != ratio){
            return Math.round((float)source*ratio/100);
        }
        return source;
    }

    private void setNullByChannelAndShowType(StatCollaborateMarketLoginResponse response, String[] showCol){
        if(null == showCol || null == response){
            return;
        }

        // 临时保存需要保留下来的数据，全部置空，后重新设置
        StatCollaborateMarketLogin responseTemp = new StatCollaborateMarketLogin();
        responseTemp.setId(response.getId());
        responseTemp.setCreateDate(response.getCreateDate());
        responseTemp.setProductId(response.getProductId());
        responseTemp.setChannelCode(response.getChannelCode());

        //动态的保存数据
        for (String col : showCol) {  //以下数字请看数据字典 key  COLLABORATE_MARKET_SHOW_TYPE 或者 CollaborateColShowEnum 的id
            if("6".equals(col)){
                responseTemp.setLoginCountA(response.getLoginCountA());
                continue;
            }
            if("7".equals(col)){
                responseTemp.setLoginCountB(response.getLoginCountB());
                continue;
            }
            if("8".equals(col)){
                responseTemp.setRegisterCountA(response.getRegisterCountA());
                continue;
            }
            if("9".equals(col)){
                responseTemp.setRegisterCountB(response.getRegisterCountB());
                continue;
            }
            if("10".equals(col)){
                responseTemp.setRegisterCountC(response.getRegisterCountC());
                continue;
            }
            if("11".equals(col)){
                responseTemp.setRegisterCountD(response.getRegisterCountD());
                continue;
            }
            if("12".equals(col)){
                responseTemp.setBpUvTotal(response.getBpUvTotal());
                continue;
            }
            if("13".equals(col)){
                responseTemp.setBpUvApi(response.getBpUvApi());
                continue;
            }
            if("14".equals(col)){
                responseTemp.setBpApiApplyCount(response.getBpApiApplyCount());
                continue;
            }
            if("15".equals(col)){
                responseTemp.setBpApiLendCount(response.getBpApiLendCount());
                continue;
            }
            if("16".equals(col)){
                responseTemp.setBpApiLendAmount(response.getBpApiLendAmount());
            }
        }

        try {
            BeanUtilsBean2.getInstance().copyProperties(response, responseTemp);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected JpaRepository<StatCollaborateMarketLogin, Long> getRepository() {
        return statCollaborateMarketLoginRepository;
    }
}
